﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class frm_Add_PartQuotation : Form
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private List<bool> byquantityList = new List<bool>(); 
        public frm_Add_PartQuotation()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            getQuotationList();
            this.quotationID.Properties.AutoComplete = true;
            getDeliveryList();
            this.priceType.Properties.AutoComplete = true;
            getPartList();
            this.partNo.Properties.AutoComplete = true;
            getCurrencyList();

            this.quantity1.EditValueChanged += quantity1_EditValueChanged;
            this.quantity2.EditValueChanged += quantity2_EditValueChanged;
            this.quantity3.EditValueChanged += quantity3_EditValueChanged;
            this.quantity4.EditValueChanged += quantity4_EditValueChanged;
            this.quantity5.EditValueChanged += quantity5_EditValueChanged;
        }

        void quantity5_EditValueChanged(object sender, EventArgs e)
        {
            
        }

        void quantity4_EditValueChanged(object sender, EventArgs e)
        {
            
        }

        void quantity3_EditValueChanged(object sender, EventArgs e)
        {
            
        }

        void quantity2_EditValueChanged(object sender, EventArgs e)
        {
            
        }

        void quantity1_EditValueChanged(object sender, EventArgs e)
        {
            
        }

        private string getPrice(string part, int qty)
        {
            string ret = null;



            return ret;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        /////////////////////////////////////
        /// Load Export Quotation List
        /////////////////////////////////////
        private void getQuotationList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT [241_ExportQuotation].QuotationID, [241_ExportQuotation].ByQuantity,"
                    + " [222_Currency].CurrencyID, [222_Currency].CurrencySymbol"
                    + " FROM [241_ExportQuotation] LEFT OUTER JOIN"
                    + " [222_Currency] ON [241_ExportQuotation].CurrencyID=[222_Currency].CurrencyID"
                    + " WHERE [241_ExportQuotation].Validity=1 AND [241_ExportQuotation].ComOrPart=0"
                    + " ORDER BY [241_ExportQuotation].QuotationID";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["QuotationID"].ToString();
                    item.Value = dataReader["QuotationID"].ToString();
                    this.quotationID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Quotation list");
            }
        }

        /////////////////////////////////////
        /// Load Delivery List
        /////////////////////////////////////
        private void getDeliveryList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT DeliveryTermID, DeliveryTermName FROM [222_DeliveryTerm] ORDER BY DeliveryTermName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["DeliveryTermName"].ToString();
                    item.Value = dataReader["DeliveryTermID"].ToString();
                    this.priceType.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {                
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Price Type list"); 
            }
        }

        ///////////////////////////////////////
        /// Load Part List
        ///////////////////////////////////////
        private void getPartList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT PartNo FROM [222_Part] ORDER BY PartNo";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["PartNo"].ToString();
                    item.Value = dataReader["PartNo"].ToString();
                    this.partNo.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Part list");
            }
        }

        /////////////////////////////////////
        /// Load Currency List
        /////////////////////////////////////
        private void getCurrencyList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CurrencyID, CurrencyName FROM [222_Currency] ORDER BY CurrencyName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CurrencyName"].ToString();
                    item.Value = dataReader["CurrencyID"].ToString();
                    this.currencySymbol.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Currency list");
            }
        }


        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;
            bool pass = true;
            bool change = false;
            bool isNum = true;

            int valueQuantity1 = 0, valueQuantity2 = 0, valueQuantity3 = 0, valueQuantity4 = 0, valueQuantity5 = 0;

            float valuePrice1 = 0, valuePrice2 = 0, valuePrice3 = 0, valuePrice4 = 0, valuePrice5 = 0;

            ComboboxItem quotaion = (ComboboxItem)quotationID.SelectedItem;
            ComboboxItem part = (ComboboxItem)partNo.SelectedItem;
            ComboboxItem delivery = (ComboboxItem)priceType.SelectedItem;

            /// Check Quotation No.
            if (pass)
            {
                if (string.IsNullOrEmpty(quotaion.Value.ToString().Trim()))
                {
                    error = "Plase Select Quotation No.";
                    pass = false;
                }
            }

            /// Check Price Type.
            if (pass)
            {
                if (string.IsNullOrEmpty(delivery.Value.ToString().Trim()))
                {
                    error = "Please select Price Type";
                    pass = false;
                }
            }

            /// Check Part ID.
            if (pass)
            {                
                if (string.IsNullOrEmpty(part.Value.ToString().Trim()))
                {
                    error = "Please select Part";
                    pass = false;
                }
            }
            
            ///////////////////////////////////
            /// Check if Part Price Exist
            ///////////////////////////////////
            if (pass)
            {
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT COUNT(ID) FROM [241_PartPrice]"
                        + " WHERE QuotationID='" + quotaion.Value.ToString() + "'"
                        + " AND PartNo='" + part.Value.ToString() + "' AND PriceType='" + delivery.Value.ToString() + "'";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    if (dataReader.Read())
                    {
                        if (Int32.Parse(dataReader[0].ToString()) > 0)
                        {
                            error = "There is one record exist in database with the same Quotation No, Part and Price Type";
                            pass = false;
                        }
                    }
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    error = "Cannot check conflict Price";
                    pass = false;
                }
            }

            //////////////////////////////////////////////////////
            /// Check if Part Exist in quotation
            //////////////////////////////////////////////////////
            if (pass)
            {
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT COUNT(ID) FROM [241_PartPrice]"
                        + " WHERE PartNo='" + part.Value.ToString() + "' AND PriceType='" + delivery.Value.ToString() + "'";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    if (dataReader.Read())
                    {
                        if (Int32.Parse(dataReader[0].ToString()) > 0)
                        {
                            if (MessageBox.Show("There is one quotation for Part. Really create new?", "Confirm add new", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                change = true;                                
                            }
                            else
                            {
                                change = false;
                                pass = false;
                            }
                        }
                    }
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    error = "Cannot check conflict quotation";
                    pass = false;
                }
            }


            /// Check Quantity 1            
            if (pass)
            {                
                if (string.IsNullOrEmpty(quantity1.Text.Trim()))
                {
                    error = "Plase enter Quantity 1";
                    pass = false;
                }
                else
                {                    
                    isNum = int.TryParse(quantity1.Text.Trim(), out valueQuantity1);
                    if (isNum)
                    {
                        if (valueQuantity1 <= 0)
                        {
                            error = "Quantity 1 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Quantity 1 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Quantity 2            
            if (pass)
            {
                if (string.IsNullOrEmpty(quantity2.Text.Trim()))
                {
                    error = "Plase enter Quantity 2";
                    pass = false;
                }
                else
                {
                    isNum = int.TryParse(quantity2.Text.Trim(), out valueQuantity2);
                    if (isNum)
                    {
                        if (valueQuantity2 <= 0)
                        {
                            error = "Quantity 2 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Quantity 2 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Quantity 3            
            if (pass)
            {
                if (string.IsNullOrEmpty(quantity3.Text.Trim()))
                {
                    error = "Plase enter Quantity 3";
                    pass = false;
                }
                else
                {
                    isNum = int.TryParse(quantity3.Text.Trim(), out valueQuantity3);
                    if (isNum)
                    {
                        if (valueQuantity3 <= 0)
                        {
                            error = "Quantity 3 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Quantity 3 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Quantity 4            
            if (pass)
            {
                if (string.IsNullOrEmpty(quantity4.Text.Trim()))
                {
                    error = "Plase enter Quantity 4";
                    pass = false;
                }
                else
                {
                    isNum = int.TryParse(quantity4.Text.Trim(), out valueQuantity4);
                    if (isNum)
                    {
                        if (valueQuantity4 <= 0)
                        {
                            error = "Quantity 4 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Quantity 4 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Quantity 5            
            if (pass)
            {
                if (string.IsNullOrEmpty(quantity5.Text.Trim()))
                {
                    error = "Plase enter Quantity 5";
                    pass = false;
                }
                else
                {
                    isNum = int.TryParse(quantity5.Text.Trim(), out valueQuantity5);
                    if (isNum)
                    {
                        if (valueQuantity5 <= 0)
                        {
                            error = "Quantity 5 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Quantity 5 must be numeric value";
                        pass = false;
                    }
                }
            }

            
            /// Check Price 1            
            if (pass)
            {
                if (string.IsNullOrEmpty(price1.Text.Trim()))
                {
                    error = "Plase enter Price 1";
                    pass = false;
                }
                else
                {
                    isNum = float.TryParse(price1.Text.Trim(), out valuePrice1);
                    if (isNum)
                    {
                        if (valuePrice1 <= 0)
                        {
                            error = "Price 1 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Price 1 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Price 2            
            if (pass)
            {
                if (string.IsNullOrEmpty(price2.Text.Trim()))
                {
                    error = "Plase enter Price 2";
                    pass = false;
                }
                else
                {
                    isNum = float.TryParse(price2.Text.Trim(), out valuePrice2);
                    if (isNum)
                    {
                        if (valuePrice2 <= 0)
                        {
                            error = "Price 2 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Price 2 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Price 3            
            if (pass)
            {
                if (string.IsNullOrEmpty(price3.Text.Trim()))
                {
                    error = "Plase enter Price 3";
                    pass = false;
                }
                else
                {
                    isNum = float.TryParse(price3.Text.Trim(), out valuePrice3);
                    if (isNum)
                    {
                        if (valuePrice3 <= 0)
                        {
                            error = "Price 3 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Price 3 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Price 4            
            if (pass)
            {
                if (string.IsNullOrEmpty(price4.Text.Trim()))
                {
                    error = "Plase enter Price 4";
                    pass = false;
                }
                else
                {
                    isNum = float.TryParse(price4.Text.Trim(), out valuePrice4);
                    if (isNum)
                    {
                        if (valuePrice4 <= 0)
                        {
                            error = "Price 4 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Price 4 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Price 5            
            if (pass)
            {
                if (string.IsNullOrEmpty(price5.Text.Trim()))
                {
                    error = "Plase enter Price 5";
                    pass = false;
                }
                else
                {
                    isNum = float.TryParse(price5.Text.Trim(), out valuePrice5);
                    if (isNum)
                    {
                        if (valuePrice5 <= 0)
                        {
                            error = "Price 5 must be > 0";
                            pass = false;
                        }
                    }
                    else
                    {
                        error = "Price 5 must be numeric value";
                        pass = false;
                    }
                }
            }

            /// Check Increase Quantity && Decrease Price
            if (quantityBasePrice.Checked)
            {
                if (pass)
                {
                    if (valueQuantity1 > valueQuantity2)
                    {
                        error = "Quantity 2 must be greater than Quantity 1";
                        pass = false;
                    }
                }

                if (pass)
                {
                    if (valueQuantity2 > valueQuantity3)
                    {
                        error = "Quantity 3 must be greater than Quantity 2";
                        pass = false;
                    }
                }

                if (pass)
                {
                    if (valueQuantity3 > valueQuantity4)
                    {
                        error = "Quantity 4 must be greater than Quantity 3";
                        pass = false;
                    }
                }

                if (pass)
                {
                    if (valueQuantity4 > valueQuantity5)
                    {
                        error = "Quantity 5 must be greater than Quantity 4";
                        pass = false;
                    }
                }
                
                if (pass)
                {
                    if (valuePrice1 < valuePrice2)
                    {
                        error = "Price 1 must be greater than Price 2";
                        pass = false;
                    }
                }

                if (pass)
                {
                    if (valuePrice2 < valuePrice3)
                    {
                        error = "Price 2 must be greater than Price 3";
                        pass = false;
                    }
                }

                if (pass)
                {
                    if (valuePrice3 < valuePrice4)
                    {
                        error = "Price 3 must be greater than Price 4";
                        pass = false;
                    }
                }

                if (pass)
                {
                    if (valuePrice4 < valuePrice5)
                    {
                        error = "Price 4 must be greater than Price 5";
                        pass = false;
                    }
                }
            }

            

            ///////////////////////////////////////////////////////
            /// Insert new Robot Quotation
            ///////////////////////////////////////////////////////
            if (pass)
            {
                if (change)
                {/*
                    try
                    {                        
                        myConnection.Open();
                        string sql = "UPDATE [241_Quotation]"
                            + " SET Status=0 WHERE PartNo='" + part.Value.ToString() + "'";
                        SqlCommand cmd_sql = new SqlCommand(sql, myConnection);                        
                        cmd_sql.ExecuteNonQuery();
                        cmd_sql.Dispose();
                        myConnection.Close();
                    }
                    catch
                    {
                        if (myConnection.State == ConnectionState.Open)
                        {
                            myConnection.Close();
                        }
                    } */
                }
                
                try
                {
                    myConnection.Open();
                    string sql = "INSERT INTO [241_PartPrice]"
                        + " (PartNo, QuotationID, Quantity1, Quantity2, Quantity3, Quantity4, Quantity5,"
                        + " Price1, Price2, Price3, Price4, Price5, PriceType, Note)"
                        + " VALUES ('" + part.Value.ToString() + "', '" + quotaion.Value.ToString() + "',"
                        + " " + valueQuantity1 + ", " + valueQuantity2 + ", " + valueQuantity3 + ","
                        + " " + valueQuantity4 + ", " + valueQuantity5 + ","
                        + " " + valuePrice1 + ", " + valuePrice2 + ", " + valuePrice3 + ", " + valuePrice4 + ", " + valuePrice5 + ","
                        + " '" + delivery.Value.ToString() + "', '" + noteText.Text + "')";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Quotation added success.");
                    clearForm();
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                    //MessageBox.Show("Cannot add Quotation. Please try again.");
                } 
            }
            else
            {
                if (!string.IsNullOrEmpty(error))
                {
                    MessageBox.Show(error);
                }
            }
        }

        private void quotationID_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboboxItem item = (ComboboxItem)this.quotationID.SelectedItem;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ByQuantity, CurrencyID"
                    + " FROM [241_ExportQuotation]"
                    + " WHERE QuotationID = '" + item.Value.ToString() + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    for (int i = 0; i < this.currencySymbol.Properties.Items.Count; i++)
                    {
                        ComboboxItem item2 = (ComboboxItem)this.currencySymbol.Properties.Items[i];
                        if (dataReader["CurrencyID"].ToString() == item2.Value.ToString())
                        {
                            this.currencySymbol.SelectedIndex = i;
                        }
                    }
                    if ((bool)dataReader["ByQuantity"])
                    {
                        this.quantityBasePrice.Checked = true;
                    }
                    else
                    {
                        this.quantityBasePrice.Checked = false;
                    }                    
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get detail for selected Quotation list");
                //MessageBox.Show(ex.Message);
            }            
        }

        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c is DevExpress.XtraEditors.TextEdit)
                {
                    ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                }

                if (c is DevExpress.XtraEditors.ComboBoxEdit)
                {
                    ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                }

                if (c is System.Windows.Forms.MaskedTextBox)
                {
                    ((System.Windows.Forms.MaskedTextBox)c).Text = null;
                }
            }
        }
    }
}
